<template>
  <div class="comment-list">
    <n-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>{{ t('menu.commentList') }}</span>
          <n-button size="small" quaternary @click="resetColumnWidths">
            <template #icon>
              <n-icon><Icons name="refresh-outline" /></n-icon>
            </template>
            重置列宽
          </n-button>
        </div>
      </template>

      <div class="search-form">
        <n-form inline :model="searchForm" :show-label="false">
          <n-form-item>
            <n-input
              v-model:value="searchForm.content"
              :placeholder="t('comment.content')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-input
              v-model:value="searchForm.username"
              :placeholder="t('comment.user')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-select
              v-model:value="searchForm.status"
              :placeholder="t('common.status')"
              clearable
              :options="statusOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              {{ t('common.search') }}
            </n-button>
            <n-button @click="handleReset" style="margin-left: 8px">
              {{ t('common.reset') }}
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1400"
        :class="{ 'resizing': isResizing }"
        @update:page="handlePageChange"
      />
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" title="评论详情" style="width: 600px">
      <div class="comment-detail" v-if="currentComment">
        <div class="detail-section">
          <h4>评论信息</h4>
          <div class="detail-item">
            <label>评论内容:</label>
            <div class="comment-content">{{ currentComment.content }}</div>
          </div>
          <div class="detail-item">
            <label>所属新闻:</label>
            <span>{{ currentComment.newsTitle }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>用户信息</h4>
          <div class="detail-item">
            <label>用户名:</label>
            <span>{{ currentComment.username }}</span>
          </div>
          <div class="detail-item">
            <label>用户ID:</label>
            <span>{{ currentComment.userId }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>统计数据</h4>
          <div class="detail-item">
            <label>点赞数:</label>
            <span>{{ currentComment.likes }}</span>
          </div>
          <div class="detail-item">
            <label>回复数:</label>
            <span>{{ currentComment.replies }}</span>
          </div>
          <div class="detail-item">
            <label>发表时间:</label>
            <span>{{ currentComment.createTime }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>状态</h4>
          <div class="detail-item">
            <label>当前状态:</label>
            <n-tag :type="getStatusType(currentComment.status)" size="small">
              {{ getStatusText(currentComment.status) }}
            </n-tag>
          </div>
        </div>

        <div class="comment-actions">
          <n-space>
            <n-button 
              v-if="currentComment.status === 'active'"
              type="warning" 
              @click="handleHide(currentComment)"
            >
              隐藏评论
            </n-button>
            <n-button 
              v-if="currentComment.status === 'hidden'"
              type="success" 
              @click="handleShow(currentComment)"
            >
              显示评论
            </n-button>
            <n-button 
              type="error" 
              @click="handleDelete(currentComment)"
            >
              删除评论
            </n-button>
          </n-space>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useI18n } from 'vue-i18n'
import { useResizableColumns } from '@/composables/useResizableColumns'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDataTable,
  NTag,
  NModal,
  NSpace,
  NAvatar,
  useMessage,
  useDialog
} from 'naive-ui'
import { 
  EyeOutline, 
  EyeOffOutline, 
  TrashOutline, 
  CheckmarkCircleOutline 
} from '@/components/Icons'
import Icons from '@/components/Icons.vue'
import { commentApi } from '@/api'

const { t } = useI18n({ useScope: 'global' })
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const showModal = ref(false)
const currentComment = ref<any>(null)

const searchForm = reactive({
  content: '',
  username: '',
  status: null
})

const tableData = ref([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => t('common.total', { count: itemCount })
})

const statusOptions = computed(() => [
  { label: t('comment.status.active'), value: 'active' },
  { label: t('comment.status.hidden'), value: 'hidden' },
  { label: t('comment.status.reported'), value: 'reported' }
])

const getStatusType = (status: string) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'hidden':
      return 'warning'
    case 'reported':
      return 'error'
    default:
      return 'default'
  }
}

const getStatusText = (status: string) => {
  return t(`comment.status.${status}`)
}

const getStatusTag = (status: string) => {
  return h(NTag, { 
    type: getStatusType(status),
    size: 'small' 
  }, () => getStatusText(status))
}

// 基础列配置
const baseColumns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    minWidth: 50,
    maxWidth: 100
  },
  {
    title: t('comment.content'),
    key: 'content',
    width: 200,
    minWidth: 150,
    maxWidth: 300,
    ellipsis: { tooltip: true }
  },
  {
    title: t('comment.user'),
    key: 'username',
    width: 120,
    minWidth: 100,
    maxWidth: 180,
    render: (row: any) => {
      return h('div', { style: 'display: flex; align-items: center;' }, [
        h(NAvatar, { 
          size: 'small', 
          src: row.userAvatar,
          fallbackSrc: '/images/default-avatar.svg',
          style: 'margin-right: 8px;'
        }),
        h('span', row.username)
      ])
    }
  },
  {
    title: t('comment.newsTitle'),
    key: 'newsTitle',
    width: 180,
    minWidth: 150,
    maxWidth: 250,
    ellipsis: { tooltip: true }
  },
  {
    title: t('common.status'),
    key: 'status',
    width: 100,
    minWidth: 80,
    maxWidth: 120,
    render: (row: any) => getStatusTag(row.status)
  },
  {
    title: t('comment.likes'),
    key: 'likes',
    width: 80,
    minWidth: 60,
    maxWidth: 120
  },
  {
    title: t('comment.replies'),
    key: 'replies',
    width: 80,
    minWidth: 60,
    maxWidth: 120
  },
  {
    title: t('common.createTime'),
    key: 'createTime',
    width: 160,
    minWidth: 120,
    maxWidth: 200
  },
  {
    title: t('common.operation'),
    key: 'actions',
    width: 240,
    minWidth: 200,
    maxWidth: 300,
    resizable: false,
    render: (row: any) => {
      const buttons = [
        h(NButton, {
          size: 'small',
          onClick: () => handleView(row)
        }, { default: () => t('common.view'), icon: () => h(NIcon, () => h(EyeOutline)) })
      ]

      if (row.status === 'active') {
        buttons.push(
          h(NButton, {
            size: 'small',
            type: 'warning',
            onClick: () => handleHide(row),
            style: { marginLeft: '8px' }
          }, { default: () => '隐藏', icon: () => h(NIcon, () => h(EyeOffOutline)) })
        )
      } else if (row.status === 'hidden') {
        buttons.push(
          h(NButton, {
            size: 'small',
            type: 'success',
            onClick: () => handleShow(row),
            style: { marginLeft: '8px' }
          }, { default: () => '显示', icon: () => h(NIcon, () => h(CheckmarkCircleOutline)) })
        )
      }

      buttons.push(
        h(NButton, {
          size: 'small',
          type: 'error',
          onClick: () => handleDelete(row),
          style: { marginLeft: '8px' }
        }, { default: () => t('common.delete'), icon: () => h(NIcon, () => h(TrashOutline)) })
      )
      
      return h('div', buttons)
    }
  }
]

// 使用可调整列宽的Hook
const { resizableColumns, resetColumnWidths, isResizing } = useResizableColumns({
  columns: baseColumns,
  tableKey: 'comment-list',
  defaultWidths: {
    'id': 60,
    'content': 200,
    'username': 120,
    'newsTitle': 180,
    'status': 100,
    'likes': 80,
    'replies': 80,
    'createTime': 160,
    'actions': 240
  }
})

const columns = computed(() => resizableColumns.value)

const loadData = async () => {
  try {
    loading.value = true
    const response = await commentApi.getList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    if (response.success) {
      tableData.value = response.data.list
      pagination.itemCount = response.data.total
    }
  } catch (error) {
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.content = ''
  searchForm.username = ''
  searchForm.status = null
  pagination.page = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleView = (row: any) => {
  currentComment.value = row
  showModal.value = true
}

const handleHide = (row: any) => {
  dialog.warning({
    title: '确认操作',
    content: `确认隐藏此评论吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await commentApi.hide(row.id)
        message.success('评论已隐藏')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleShow = (row: any) => {
  dialog.info({
    title: '确认操作',
    content: `确认显示此评论吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await commentApi.show(row.id)
        message.success('评论已显示')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleDelete = (row: any) => {
  dialog.error({
    title: '确认删除',
    content: `确认删除此评论吗？删除后将无法恢复。`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await commentApi.delete(row.id)
        message.success('评论已删除')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.comment-detail {
  padding: 16px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 8px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: bold;
  margin-right: 12px;
  width: 80px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 4px;
  word-break: break-word;
}

.comment-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
  text-align: center;
}
</style>